//
//  UserDefaultsExtension.swift
//  JKTools
//
//  Created by 姜奎 on 2024/11/22.
//

import Foundation

extension UserDefaults {

    private static let BookmarkDatasKey = "com.jk.JKTools.BookmarkDatasKey"

    static func readBookmarkData(by url: URL?) -> URL? {
        guard let url = url else { return nil }
        guard let bookmarkDatas = UserDefaults.standard.dictionary(forKey: Self.BookmarkDatasKey) else {
            return nil
        }

        guard let bookmarkData = bookmarkDatas[url.absoluteString] as? Data else {
            return nil
        }

        var isStale = false
        guard let binDirectory = try? URL(resolvingBookmarkData: bookmarkData, options: URL.BookmarkResolutionOptions.withSecurityScope, relativeTo: nil, bookmarkDataIsStale: &isStale) else {
            return nil
        }

        return binDirectory
    }

    static func writeBookmarkData(by url: URL?) -> URL? {
        guard let url = url else { return nil }
        guard let bookmarkData = try? url.bookmarkData(options: URL.BookmarkCreationOptions.withSecurityScope, includingResourceValuesForKeys: nil, relativeTo: nil) else {
            return nil
        }

        var bookmarkDatas = UserDefaults.standard.dictionary(forKey: Self.BookmarkDatasKey) ?? [:]

        bookmarkDatas[url.absoluteString] = bookmarkData

        UserDefaults.standard.setValue(bookmarkDatas, forKey: Self.BookmarkDatasKey)
        return url
    }

    static func cleanBookmarkDatas() {
        UserDefaults.standard.removeObject(forKey: Self.BookmarkDatasKey)
    }

    static func checkAndRegisterFirstStartApp() -> Bool {
        guard UserDefaults.standard.bool(forKey: "com.jk.JKTools.registerFirstStartApp") != true else {
            return false
        }

        UserDefaults.standard.set(true, forKey: "com.jk.JKTools.registerFirstStartApp")

        return true
    }
}
